﻿using System;
using System.Globalization;
using System.Threading.Tasks;
using System.Web.Http;
using Top.Web;
using Top.Web.Api;
using Top.PointStore.Business;
using Top.PointStore.Web.Filters;
using Top.Web.Api.Filters;
using Top.Core;
using System.Diagnostics;
//using Top.PointStore.Filters;

namespace Top.PointStore.Controllers
{
    /// <summary>
    /// 积分
    /// </summary>    
    public class PointController : ApiBase
    {
        public static bool SyncLock = false;
        /// <summary>根据用户ID得到一条记录
        /// </summary>
        /// <returns></returns>
        [NoLogin][NoIdempotent]
        public object Get()
        {
            try
            {
                return GlobalResourceManager.CheckPointMainIsExist(User);
            }
            catch (Exception ex)
            {
                //Trace.Write(ex, "获取个人积分异常");
                throw new WebApiException("系统正忙，请稍后刷新");
            }           
        }

        [NoLogin]
        [NoIdempotent]
        public async Task<object> GetV3()
        {
            int adminKid = Get("adminKid", 0);
            string accessToken = Get("accessToken", "");
            string userToken = Get("userToken", "");
            string uk = Get("uk", "");
            if (string.IsNullOrWhiteSpace(userToken))
            {
                userToken = uk;
            }
            string ak = Post("ak", "");
            if (string.IsNullOrWhiteSpace(accessToken))
            {
                accessToken = ak;
            }
            OAuthUser user = OAuthInfoManager.GetOAuthUserByGuid(adminKid, accessToken, userToken, "S_Admin");
            GlobalResourceManager.CheckUserTokenIsExist(user);
            T_PointMain_new pointMain = GlobalResourceManager.CheckPointMainIsExist(user);
            return pointMain;
        }

        [NoLogin]
        [NoIdempotent]
        public async Task<object> GetV4()
        {

            int brokerKid = Get("userKid", 0);
            string accessToken = Get("accessToken", "");
            string userToken = Get("userToken", "");
            string uk = Get("uk", "");
            if (string.IsNullOrWhiteSpace(userToken))
            {
                userToken = uk;
            }
            string ak = Post("ak", "");
            if (string.IsNullOrWhiteSpace(accessToken))
            {
                accessToken = ak;
            }
            OAuthUser user = OAuthInfoManager.GetOAuthUserByGuid(brokerKid, accessToken, userToken, "T_Broker");
            GlobalResourceManager.CheckUserTokenIsExist(user);
            T_PointMain_new pointMain = GlobalResourceManager.CheckPointMainIsExist(user);
            return pointMain;
        }

        [NoLogin]
        public object Club_SyncPoint()
        {
            if (SyncLock)
            {
                throw new WebApiException("接口请求太过频繁或正被占用");
            }
            try
            {
                SyncLock = true;                
                string userKids = Post("kid", "");
                if (string.IsNullOrWhiteSpace(userKids))
                {
                    userKids = Get("kid", "");
                }
                string[] kids = userKids.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                if (kids.Length > 2000)
                {
                    throw new WebApiException("超出最大值2000限制");
                }
                if (kids.Length<1)
                {
                    return null;
                }
                return PointManager.GetAssignPoint(userKids);
            }
            catch
            {
                throw new WebApiException("拉取数据出错");
            }
            finally
            {
                SyncLock = false;
            }                      
        }
             
        /// <summary>
        /// 更新用户积分
        /// </summary>
        /// <param name="brokerKid"></param>
        /// <param name="adminKid"></param>
        /// <param name="point"></param>
        /// <param name="pointCode"></param>
        /// <param name="time"></param>
        /// <param name="token"></param>
        /// <param name="userToken"></param>
        /// <returns></returns>
        [NoLogin]
        public object UpdateUserPoint(int point, string pointCode, string time, string token, int brokerKid = 0, int adminKid = 0, string userToken = "")
        {
            CheckRequest(userToken, point, pointCode, time, token);
            return PointManager.UpdateUserPoint(userToken, point, pointCode);
        }

        private void CheckRequest(string userToken, int point, string pointCode, string time, string token)
        {
            var now = DateTime.Now;
            if (string.IsNullOrEmpty(time))
                throw new WebApiException("时间不能为空");

            DateTime dateTime;
            if (!DateTime.TryParseExact(time, "yyyyMMddHHmmss", null, DateTimeStyles.None, out dateTime))
                throw new WebApiException("时间格式错误");

            var timeSpan = now.Subtract(dateTime).TotalMinutes;
            timeSpan = timeSpan > 0 ? timeSpan : -timeSpan;
            if (timeSpan > 5)
                throw new WebApiException("请求已过期");

            if (string.IsNullOrEmpty(token))
                throw new WebApiException("token不能为空");

            var guidToken2 = WebHelper.MD5(time + Top.Common.TopConfigHelper.GetAppSettings("EncryptKey"));
            if (token != guidToken2)
                throw new WebApiException("token异常");
        }

        /// <summary>
        /// 对接二手房积分接口
        /// </summary>
        /// <param name="brokerId">经纪人ID</param>
        /// <param name="point">积分</param>
        /// <param name="operAction">行为代码</param>
        /// <returns></returns>
        [NoLogin]
        public async Task<object> SubmitPoint(string operAction, int point = 0)
        {
            int brokerId = Get("brokerId", 0);
            string accessToken = Get("accessToken", "");
            string userToken = Get("userToken", "");
            string uk = Get("uk", "");
            if (string.IsNullOrWhiteSpace(userToken))
            {
                userToken = uk;
            }
            string ak = Post("ak", "");
            if (string.IsNullOrWhiteSpace(accessToken))
            {
                accessToken = ak;
            }
            OAuthUser user = OAuthInfoManager.GetOAuthUserByGuid(brokerId, accessToken, userToken, "T_Broker");
            GlobalResourceManager.CheckUserTokenIsExist(user);
            T_PointMain_new pointMain = GlobalResourceManager.CheckPointMainIsExist(user);
            return PointManager.SubmitPoint(operAction,0, 200, user,pointMain,true);
        }

        /// <summary>
        /// 对接一手房积分接口
        /// </summary>
        /// <param name="pointCode">行为代码</param>
        /// <param name="buildingKid">楼盘ID</param>
        /// <param name="userId"></param>
        /// <param name="userSource">来源 1、CRM  S_Admin 2、经纪人T_Broker</param>
        /// <param name="pointSource">积分来源APP：500，微信：400, WEB:300,二手房：200</param>
        /// <returns></returns>
        [NoLogin]
        public async Task<object> AddPoint(string pointCode, int buildingKid, int pointSource)
        {
            int userId = Get("userId", 0);
            int userSource = Get("userSource", 0);
            if (userSource==0)
            {
                userSource = Get("source", 0);
            }
            string accessToken = Get("accessToken", "");
            string userToken = Get("userToken", "");
            string uk = Get("uk", "");            
            if (string.IsNullOrWhiteSpace(userToken))
            {
                userToken = uk;
            }
            string ak = Post("ak", "");
            if (string.IsNullOrWhiteSpace(accessToken))
            {
                accessToken = ak;
            }
            OAuthUser user = default(OAuthUser);            
            if (userSource == 2)
            {
                user = OAuthInfoManager.GetOAuthUserByGuid(userId, accessToken, userToken, "T_Broker");
            }
            else if (userSource == 1 || userSource == 3)
            {
                user = OAuthInfoManager.GetOAuthUserByGuid(userId, accessToken, userToken, "S_Admin");
            }
            GlobalResourceManager.CheckUserTokenIsExist(user);
            T_PointMain_new pointMain = GlobalResourceManager.CheckPointMainIsExist(user);
            return PointManager.SubmitPoint(pointCode, buildingKid, pointSource,user,pointMain);
        }
        /// <summary>
        /// 对接一手房积分接口
        /// </summary>
        /// <param name="pointCode">行为代码</param>
        /// <param name="buildingKid">楼盘ID</param>
        /// <param name="userId"></param>
        /// <param name="userSource">来源 1、CRM  S_Admin 2、经纪人T_Broker</param>
        /// <param name="pointSource">积分来源APP：500，微信：400, WEB:300,二手房：200</param>
        /// <param name="userSource">T_Broker----2    S_Admin-------1、3 </param>
        /// <returns></returns>
        [NoLogin]
        public async Task<object> AddPointV1(string pointCode, int buildingKid, int pointSource, int userSource = 2)
        {
            int userId = Get("userId", 0);
            string accessToken = Get("accessToken", "");
            string userToken = Get("userToken", "");
            string uk = Get("uk", "");
            if (string.IsNullOrWhiteSpace(userToken))
            {
                userToken = uk;
            }
            string ak = Post("ak", "");
            if (string.IsNullOrWhiteSpace(accessToken))
            {
                accessToken = ak;
            }
            OAuthUser user = default(OAuthUser);
            if (userSource == 2)
            {
                user = OAuthInfoManager.GetOAuthUserByGuid(userId, accessToken, userToken, "T_Broker");
            }
            else if (userSource == 1 || userSource == 3)
            {
                user = OAuthInfoManager.GetOAuthUserByGuid(userId, accessToken, userToken, "S_Admin");
            }
            GlobalResourceManager.CheckUserTokenIsExist(user);
            T_PointMain_new pointMain = GlobalResourceManager.CheckPointMainIsExist(user);
            return PointManager.SubmitPoint(pointCode, buildingKid, pointSource, user, pointMain);
        }
        /// <summary>
        /// 签到
        /// </summary>
        /// <param name="userKid"></param>
        /// <param name="userType"></param>
        /// <returns></returns>
        [NoLogin]
        public async Task<object> SignIn(int userKid = 0, string userType = "")
        {
            string accessToken = Get("accessToken", "");
            string userToken = Get("userToken", "");
            string uk = Get("uk", "");
            if (string.IsNullOrWhiteSpace(userToken))
            {
                userToken = uk;
            }
            string ak = Post("ak", "");
            if (string.IsNullOrWhiteSpace(accessToken))
            {
                accessToken = ak;
            }
            OAuthUser user = OAuthInfoManager.GetOAuthUserByGuid(userKid, accessToken, userToken, userType);
            GlobalResourceManager.CheckUserTokenIsExist(user);
            T_PointMain_new pointMain = GlobalResourceManager.CheckPointMainIsExist(user);
            return PointManager.UserSignIn(user,pointMain, "api.all.signin");
        }

        [NoLogin]
        public async Task<object> CheckSignIn(int userKid = 0, string userType = "")
        {
            string accessToken = Get("accessToken", "");
            string userToken = Get("userToken", "");
            string uk = Get("uk", "");
            if (string.IsNullOrWhiteSpace(userToken))
            {
                userToken = uk;
            }
            string ak = Post("ak", "");
            if (string.IsNullOrWhiteSpace(accessToken))
            {
                accessToken = ak;
            }
            OAuthUser user = OAuthInfoManager.GetOAuthUserByGuid(userKid, accessToken, userToken, userType);
            GlobalResourceManager.CheckUserTokenIsExist(user);
            T_PointMain_new pointMain = GlobalResourceManager.CheckPointMainIsExist(user);
            return PointManager.CheckSignIn(user,"api.all.signin");
        }

        [NoLogin]
        public async Task<object> GetUserPointMain(string userPhone,int pageIndex=1,int pageSize=12)
        {
            return await PointManager.GetUserPointMain(userPhone,new Pager(pageIndex,pageSize));
        }

        [NoLogin]
        public object SetUserPointMain(string userToken, int pointAll, int pointBalance, int pointCash)
        {
            return PointManager.SetUserPointMain(pointAll, pointBalance, pointCash, userToken);
        }

        [NoLogin]
        public async Task<object> GetTodayPoint(int userKid = 0, string userType = "")
        {
            string accessToken = Get("accessToken", "");
            string userToken = Get("userToken", "");
            string uk = Get("uk", "");
            if (string.IsNullOrWhiteSpace(userToken))
            {
                userToken = uk;
            }
            string ak = Post("ak", "");
            if (string.IsNullOrWhiteSpace(accessToken))
            {
                accessToken = ak;
            }
            OAuthUser user = OAuthInfoManager.GetOAuthUserByGuid(userKid, accessToken, userToken, userType);
            GlobalResourceManager.CheckUserTokenIsExist(user);
            T_PointMain_new pointMain = GlobalResourceManager.CheckPointMainIsExist(user);          
            return PointManager.GetTodayPoint(pointMain);
        }

        [NoLogin]
        public int test()
        {
            return 1;
        }
    }
}
